<template>
 <!-- 服务清单 -->
    <div>
        <div class="e-table" style="background-color: #fff" v-if="showTable">
            <!-- 头部buttons -->
            <div class="top" v-if="isAdd">
                <div class="left">
                    <div>
                        <el-button size="small" type="primary"  class="btn-greenYellow" plain @click="addData">新增</el-button>
                        <el-button size="small" type="danger" class="btn-delete"  plain @click="deleteData">批量删除</el-button>
                    </div>
                </div>
            </div>
            <div>
                <div class="errorMsg" v-if="errorMsg.length>0">
                    <span >
                        {{ errorMsg.join(',') }}
                    </span>
                </div>
                <el-table ref="tableRef"
                        border
                        style="width: 100%"
                        :data="tableData"
                        :row-class-name="tableRowClassName"
                        @selection-change="changeSelect"
                        class="table"
                    :max-height="$store.state.tableHeight"
                    >
                        <el-table-column v-if="state === 0" type="selection" width="50">
                        </el-table-column>
                        <el-table-column
                            label="序号"
                            type="index"
                            width="100"
                            align="center"
                        >
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            fixed
                            width="100px"
                            v-if="state === 0"
                            >
                            <template slot-scope="{ row }">
                                <div class="list_box">
                                    <img src="@/assets/btn/delete.png" class="cancel_delete"
                                        @click="deleteEle(row)"
                                        v-if="isAdd"
                                        title="删除"
                                    />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="typeId"
                            label="服务类型"
                            min-width="200"
                        >
                            <template slot-scope="{ row }">
                                <el-select v-model="row.typeId" @change="changeTypeId(row)" v-if="isAdd">
                                    <el-option
                                        v-for="item in serverType"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                                <span v-else>{{ row.typeName }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="name"
                            label="名称"
                            min-width="200"
                            align="left"
                        >
                            <template slot-scope="{ row }">
                                <el-input v-model="row.name" v-if="isAdd" @change="input(row)"></el-input>
                                <span v-else>{{ row.name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="quantity"
                            label="数量"
                            width="200"
                            align="right"
                        >
                            <template slot-scope="{ row }">
                                <el-input v-if="isEdit" v-model="row.quantity" v-enterJustFloat2 @change="onCalcAmount(row,'quantityUpdateFlag')" ></el-input>
                                <span v-else>{{ row.quantity }}</span>
                                <historyUpdateTable
                                    v-if="checkEmpty(row.numberRecords)"
                                    @clickIcon="clickIcon(row.numberRecords)"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="unitPrice"
                            label="单价(元)"
                            width="200"
                            align="right"
                        >
                            <template slot-scope="{ row }">
                                <el-input v-if="isEdit" v-model="row.unitPrice" v-enterJustFloat @change="onCalcAmount(row,'unitPriceUpdateFlag')"></el-input>
                                <span v-else>{{ row.unitPrice }}</span>
                                <historyUpdateTable
                                    v-if="checkEmpty(row.priceRecords)"
                                    @clickIcon="clickIcon(row.priceRecords)"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column prop="amount" width="200" label="金额(元)" align="right">
                            <template slot-scope="{ row }">
                                <span>{{ row.amount }}</span>
                                <historyUpdateTable
                                    v-if="checkEmpty(row.amountRecords)"
                                    @clickIcon="clickIcon(row.amountRecords)"
                                />
                            </template>
                        </el-table-column>
                </el-table>
            </div>
         </div>
    </div>
</template>
<script>
import { isFourInput, isNumInput, isTwoInput, isFourInputJust } from '@/utils/rules.js'
import { mapState, mapMutations } from 'vuex'
// import { selectDataClient } from '@/utils/common'
import historyUpdateTable from '@/pages/balanceContract/materialContract/ctMaterialPurchase/components/historyUpdateTable.vue'
import fn from '@/utils/checkEmpty.js'
export default {
    props: {
        detailsOfProposed: {
            type: Array,
            default: function () {
                return []
            }
        },
        tenderClass: {
            type: String,
            default: ''
        },
        billid: {
            type: String,
            default: ''
        },
        contractListTable: {
            default: function () {
                return []
            }
        },
        errorMsg: {
            type: Array,
            default: function () {
                return []
            }
        },
        isBidding: {
            type: Boolean,
            default: false
        },
        mainInfo: {
            type: Object,
            default: function () {
                return {}
            }
        },
        auditState: {
            type: Object,
            default: function () {
                return {
                    canAudit: false,
                    canModify: true,
                    canUndoAudit: false,
                    freeNextUnits: [],
                    isFree: false,
                }
            }
        },
        //是否可以新增
        isAdd: {
            default: true
        },
        //是否可以编辑
        isEdit: {
            default: true
        },
        subcontract: { //接口
        },
        state: { //流程状态
            type: Number
        }
    },
    model: {
        prop: 'contractListTable',
        event: 'change'
    },
    computed: {
        tenderId () {
            return this.$route.query.billid
        },
        ...mapState({
            serverList: state => state.contract.ctClassify.serverList, //服务清单数据
            supplyType: state => state.contract.ctClassify.supplyTypeList
        }),
        //判断数据是否为空
        checkEmpty () {
            return datas=>{
                return !fn.checkEmpty(datas)
            }
        },
    },
    components: {
        historyUpdateTable,
    },
    watch: {
        contractListTable: {
            handler (newName) {
                this.tableData = newName
            },
            immediate: false,
            deep: true
        },
        tableData: {
            handler (newName) {
                this.$emit('change', newName)
            },
            immediate: true,
            deep: true
        },
        serverList: {
            handler (newData) { //计算服务清单
                newData.forEach(item=>{
                    if(!this.tableData.find(x=>x.oriBillId === item.oriBillId)) {
                        item.amount = (parseFloat(item.quantity) * parseFloat(item.unitPrice)).toFixed(2)
                        this.tableData.push(item)
                    }
                })
            },
            immediate: false,
            deep: true
        },
    },
    data () {
        return {
            detailsOfProposedArr: [],
            tableData: [],
            mapTableData: {},
            addList: [], // 缓存新增数据
            unitList: [],
            searchKey: '',
            isSearch: false,
            addFlag: true,
            materialListTeam: [], //存储执行队列
            materialListIndex: 0,
            showTable: true,
            serverType: [
                { value: 1, label: '设备维修' },
                { value: 2, label: '物流运输' },
                { value: 3, label: '设备安装' },
            ],
            tableSelect: []
        }
    },
    created () {
        this.getData()
    },
    mounted () {
        this.setServerList([])
    },
    methods: {
        ...mapMutations(
            'contract', ['setServerList']
        ),
        ...mapMutations(['setHistoryTableData']),
        // 获取列表数据
        getData () {
            this.showTable = false
            //获取设备清单
            this.subcontract.getServerList({
                sourceId: this.billid,
            }).then(res => {
                res = res.code ? [] : res
                res.forEach(item=>{
                    item.typeId = parseInt(item.typeId)
                    item.changeType = 0
                    if(this.state === 1) {
                        item.quantityUpdateFlag = false
                        item.unitPriceUpdateFlag = false
                        item.amountUpdateFlag = false
                    }
                })
                this.tableData = res
                this.showTable = true
            })
        },
        // 输入后计划金额
        onCalcAmount (row, feild) {
            this.$emit('isMonitorTaxRate')
            if(this.state === 1) {
                row.amountUpdateFlag = true
                row[feild] = true
            }
            row.amount = row.changeType !== -1 ?  ( parseFloat(row.quantity ? row.quantity : 0) * parseFloat(row.unitPrice ? row.unitPrice : 0) ).toFixed(2)  : 0
            if(row.changeType !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
            }

        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                return `class-${row.billId} row-hide`
            }else{
                return `class-${row.billId} row-show`
            }

        },
        isFourInput (event) {
            isFourInput(event)
        },
        isFourInputJust (event) {
            isFourInputJust(event)
        },
        isNumInput (event) {
            isNumInput(event)
        },
        isTwoInput (event) {
            isTwoInput(event)
        },
        //单价类型切换
        unitPriceTypeChange (row) {
            const fn = data=>{
                data.forEach(item=>{
                    item.unitPriceType = row.unitPriceType
                    if(!item.isDetailed) {
                        fn(item.children)
                    }
                    this.mapTableData[row.billid] = row
                })
            }
            if(!row.isDetailed) {
                fn(row)
            }else{
                this.mapTableData[row.billid] = row
            }
        },
        //单价切换
        unitPriceChange (row) {
            row.children.forEach(item=>{
                item.unitPrice = row.unitPrice
                this.mapTableData[item.billid] = item
                this.onCalcAmount(item)
            })
            this.mapTableData[row.billid] = row
        },
        //数量切换
        quantityChange (row) {
            const parent = this.mapTableData[row.parentId]
            // 统计所有同级
            const countSibling = parent.children.reduce((prev, item) => {
                return prev + Math.round(item.changeType !== -1 ? item.quantity : 0)
            }, 0)
            // 赋值汇总数据给父级
            parent.quantity = countSibling // 赋值汇总数据给父级
        },
        clickIcon (list) {
            this.setHistoryTableData(list)
        },
        addData () {
            const obj = {
                'amount': 0,
                'billId': '',
                'changeState': 0,
                'changeType': 1,
                'name': '',
                'oneLevelTypeId': '',
                'oneLevelTypeName': '',
                'quantity': 0,
                'sourceId': this.billid,
                'specificationModel': '',
                'textureOfMaterial': '',
                'typeId': 1,
                'typeName': '工程消耗',
                'unit': '',
                'unitPrice': '',
                'oriUnitPrice': '', //原单价
                'oriQuantity': '', //原单价
                'oriBillId': '', //原id
            }
            this.tableData.push(obj)
        },
        deleteData () {
            if(this.tableSelect.length === 0) return
            this.clientPop('err', this.moreDeleteListErr(this.tableSelect), () => {
                this.$emit('isMonitorTaxRate')
                this.tableSelect.forEach(item=>{
                    if(item.changeType === 1 ) {
                        let index = this.tableData.findIndex(x=>x === item)
                        this.tableData.splice(index, 1)
                    }else{
                        item.changeType = -1
                    }
                })
            })
        },
        deleteEle (row) {
            this.clientPop('err', this.oneDeleteListErr, () => {
                this.$emit('isMonitorTaxRate')
                if(row.changeType === 1 ) {
                    let index = this.tableData.findIndex(x=>x === row)
                    this.tableData.splice(index, 1)
                }else{
                    row.changeType = -1
                }
            })
        },
        changeSelect (selection) {
            this.tableSelect = selection
        },
        changeTypeId (row) {
            if( !row.typeId )return
            row.typeName = this.serverType.find(x => x.value === row.typeId).label
            this.input(row)
        },
        //改变changeType
        input (row) {
            if(row.changeType !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
            }
        },
        //清除数据
        clearData () {
            for(let i = 0;i < this.tableData.length;i++) {
                if( this.tableData[i].changeType === 1 ) {
                    this.tableData.splice(i, 1)
                    i--
                }else{
                    this.tableData[i].changeType = -1
                }
            }
        },
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
</style>
